package com.yunchang.spring.visitor.demo.utils;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.JsonNodeType;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public abstract class JsonUtil {
	
	private static ObjectMapper objectMapper = new ObjectMapper();
	 
	 static {
		 objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
	 }

	public static String toJson(Object o) {
		try {
			return objectMapper.writeValueAsString(o);
		} catch(Exception e) {
		}
		return null;
	}
	
	/**
	 * 从指定json字符串包装成指定类型T对象返回
	 * @param strInfo 指定json字符串
	 * @param T 转化的对象类型
	 * @return 转化成功，返回指定类型T对象返回；否则返回null
	 */
	public static <T> T toObject(String strInfo, Class<T> T) {
        if (StringUtils.isEmpty(strInfo)) {
            return null;
        }
		try {
			return objectMapper.readValue(strInfo, T);
		} catch (Exception e) {
		}
		return null;
	}

	public static Map<String, String> getMap(String json) {
		try {
			Map<String, String> result = new HashMap<>();
			JsonNode node = objectMapper.readTree(json);
			if (!node.isObject()) {
				// 如果不是json map，则返回null
				return null;
			}
			Iterator<Map.Entry<String, JsonNode>> it = node.fields();
			while (it.hasNext()) {
				Map.Entry<String, JsonNode> entry = it.next();
				JsonNode child = entry.getValue();
				if (child != null) {
					if (child.isValueNode()) {
						if (child.getNodeType() == JsonNodeType.STRING) {
							result.put(entry.getKey(), child.textValue());
						} else {
							result.put(entry.getKey(), child.toString());
						}
					} else {
						result.put(entry.getKey(), child.toString());
					}
				}
			}
			return result;
		}catch (Exception e) {
			return null;
		}
	}
}
